package com.pope.framework.triage.modular.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pope.framework.core.reqres.response.ResponseData;
import com.pope.framework.core.util.StringUtil;
import com.pope.framework.dict.modular.entity.DictRescueWhere;
import com.pope.framework.dict.modular.service.DictRescueWhereService;
import com.pope.framework.kernel.model.exception.ServiceException;
import com.pope.framework.kernel.model.page.PageResult;
import com.pope.framework.page.PageFactory;
import com.pope.framework.rescue.modular.dto.RescueInfoDto;
import com.pope.framework.rescue.modular.entity.RescueInfo;
import com.pope.framework.rescue.modular.entity.RescueLog;
import com.pope.framework.rescue.modular.service.RescueInfoService;
import com.pope.framework.rescue.modular.service.RescueLogService;
import com.pope.framework.rescue.modular.vo.VisitVo;
import com.pope.framework.third.ThirdUtil;
import com.pope.framework.triage.modular.entity.GradeInfo;
import com.pope.framework.triage.modular.entity.PatientInfo;
import com.pope.framework.triage.modular.entity.TriageInfo;
import com.pope.framework.triage.modular.service.GradeInfoService;
import com.pope.framework.triage.modular.service.PatientInfoService;
import com.pope.framework.triage.modular.service.TriageInfoService;
import com.pope.framework.triage.modular.vo.PatientInfoVo;
import com.pope.framework.triage.modular.vo.RescueLogVo;
import com.pope.framework.triage.modular.vo.TriageSimpleInfoVo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;

@RestController
@RequestMapping("${spring.application.app-id}/rescue")
@Api(value="离抢信息相关API",tags= {"离抢信息相关API"})
//@CrossOrigin(allowCredentials="true",maxAge = 3600)
@CrossOrigin
public class RescueController {

	@Autowired
	private PatientInfoService patientInfoService;
	
	@Autowired
	private TriageInfoService triageInfoService;
	@Autowired
	private GradeInfoService gradeInfoService;
	@Autowired
	private RescueInfoService rescueInfoService;
	
	@Autowired
	private RescueLogService rescueLogService;
	@Autowired
	
	private DictRescueWhereService dictRescueWhereService;
	
	@Autowired
	private ThirdUtil thirdUtil;

	
	@GetMapping("list")
	@ApiOperation(value = "查询离抢左侧列表信息信息",notes = "查询离抢左侧列表信息信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "患者名称",dataType = "String",paramType = "query",example = "张三"),
            @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd",dataType = "String",paramType = "query",example = "2018-01-02"),
            @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd",dataType = "String",paramType = "query",example = "2018-01-02"),
            @ApiImplicitParam(name = "triageState",value = "分诊状态1待评估2已评估",dataType = "String",paramType = "query",example = "1"),
            @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "Integer",paramType = "query",example = "1"),
            @ApiImplicitParam(name = "emergencyNumber",value = "分诊编号",dataType = "String",paramType = "query",example = "10"),
            @ApiImplicitParam(name = "pagestart",value = "第几页，从1开始，默认为1",dataType = "String",paramType = "query",example = "1"),
            @ApiImplicitParam(name = "pagenum",value = "每页显示记录数，默认为20",dataType = "String",paramType = "query",example = "10"),
            @ApiImplicitParam(name = "orderby",value = "排序字段，默认为主键ID，可排序字段有id，name患者姓名，depart部门ID，updatetime分诊时间",dataType = "String",paramType = "query",example = "id"),
            @ApiImplicitParam(name = "sort",value = "排序方式，有asc,desc,默认为主键asc",dataType = "String",paramType = "query",example = "desc"),
            
    })
	@ApiResponse(code=1,message="返回对象",response=TriageSimpleInfoVo.class,responseContainer="List")
	public ResponseData<PageResult<TriageSimpleInfoVo>> list(String name,String beginDate,String endDate,String triageState,Integer hospitalId,String emergencyNumber){		
		Page<TriageSimpleInfoVo> page=PageFactory.defaultPage();
		
//    	QueryWrapper<TriageInfo> wrapper=new QueryWrapper<TriageInfo>();
//    	//wrapper.setEntity(triageInfo);
		IPage<TriageSimpleInfoVo> data=rescueInfoService.listSimple(page,  name, beginDate, endDate,triageState,hospitalId,emergencyNumber);
		
		return ResponseData.success(PageFactory.pageResult(data));
	}
	
	@ApiOperation(value = "根据分诊ID获取离抢信息",notes = "根据分诊ID获取离抢信息")
    @ApiImplicitParam(name = "triageId",value = "分诊ID",dataType = "Integer",paramType = "path",example = "1112",required=true)
	@GetMapping("triageId/{triageId}")
	public ResponseData<VisitVo> selectByTriageId(@PathVariable Integer triageId){
		if(triageId==null) {
			throw new ServiceException("分诊ID不能为空，请重新确认！");
		}
		TriageInfo triageInfo=triageInfoService.getById(triageId);
		if(triageInfo==null) {
			throw new ServiceException("该分诊信息不存在");
		}
		PatientInfo patientInfo=null;
		if(triageInfo.getPatientId()!=null) {
			PatientInfo queryPatientInfo=new PatientInfo();
			queryPatientInfo.setId(triageInfo.getPatientId());
			QueryWrapper<PatientInfo> queryPatientInfoWrapper=new QueryWrapper<>();
			queryPatientInfoWrapper.setEntity(queryPatientInfo);
			patientInfo=patientInfoService.getOne(queryPatientInfoWrapper);
		}
		
		
		
		PatientInfoVo patientInfoVo=null;
		if(patientInfo!=null) {
			patientInfoVo=patientInfoService.getPatientDisplay(patientInfo);
		}
		return ResponseData.success(createVisitVo(triageInfo,patientInfoVo));
	}
	
	@ApiOperation(value = "根据身份证号患者就诊信息",notes = "根据身份证号读取患者就诊信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "idNum",value = "身份证号",dataType = "String",paramType = "path",example = "1112",required=true),
		@ApiImplicitParam(name = "hospitalId",value = "登陆用户所在的医院ID",dataType = "Integer",paramType = "query",example = "1112",required=true)
	})
    
	
	@GetMapping("idNum/{idNum}")
	public ResponseData<VisitVo> selectByIdNum(@PathVariable String idNum,Integer hospitalId){
		if(StrUtil.isEmpty(idNum)) {
			throw new ServiceException("患者idNum不能为空，请重新确认！");
		}
		if(hospitalId==null) {
			throw new ServiceException("登陆用户所在的医院ID不能为空，请重新确认！");
		}

		PatientInfo queryPatientInfo=new PatientInfo();
		queryPatientInfo.setIdNumber(idNum.trim());
		queryPatientInfo.setHospitalId(hospitalId);
		QueryWrapper<PatientInfo> queryPatientInfoWrapper=new QueryWrapper<>();
		queryPatientInfoWrapper.setEntity(queryPatientInfo);
		
		PatientInfo patientInfo=patientInfoService.getOne(queryPatientInfoWrapper);
		PatientInfoVo patientInfoVo=null;
		if(patientInfo!=null) {
			patientInfoVo=patientInfoService.getPatientDisplay(patientInfo);
		}else {
			throw new ServiceException("该患者不存在！");
		}
		return ResponseData.success(createVisitVo(null,patientInfoVo));
	}
	
	
	private VisitVo createVisitVo(TriageInfo triageInfo,PatientInfoVo patientInfoVo) {
		RescueInfo queryRescueInfo=new RescueInfo();
		if(triageInfo==null) {
			queryRescueInfo.setPatientId(patientInfoVo.getId());
		}else {
			queryRescueInfo.setTriageId(triageInfo.getId());
		}
		QueryWrapper<RescueInfo> queryRescueInfoWrapper=new QueryWrapper<>();
		queryRescueInfoWrapper.setEntity(queryRescueInfo);
		queryRescueInfoWrapper.orderByDesc("UPDATETIME");
		RescueInfo rescueInfo=rescueInfoService.getOne(queryRescueInfoWrapper);
		VisitVo visitVo=new VisitVo();
		if(triageInfo==null) {
			TriageInfo queryTriageInfo=new TriageInfo();
			queryTriageInfo.setPatientId(patientInfoVo.getId());
			QueryWrapper<TriageInfo> queryTriageInfoWrapper=new QueryWrapper<>();
			queryTriageInfoWrapper.setEntity(queryTriageInfo);
			queryTriageInfoWrapper.orderByDesc("UPDATETIME");
			 triageInfo=triageInfoService.getOne(queryTriageInfoWrapper);
			if(triageInfo==null) {
				throw new ServiceException("该患者没有就诊记录，请重写确认！");
			}
		}
		if(rescueInfo==null) {
			
			visitVo.setPatientInfoVo(patientInfoVo);
			visitVo.setDepart(triageInfo.getDepart());
			visitVo.setVisitTime(triageInfo.getCreatetime());
			visitVo.setTriageId(triageInfo.getId());
			visitVo.setHospitalId(triageInfo.getHospitalId());
			visitVo.setPatientId(triageInfo.getPatientId());
		}
		else{
			BeanUtil.copyProperties(rescueInfo, visitVo);
			visitVo.setPatientInfoVo(patientInfoVo);
			
		}
		visitVo.setComingGradeId(triageInfo.getComingGrade());
		visitVo.setChangeGradeId(triageInfo.getChangeGrade());
		visitVo.setAutoGradeId(triageInfo.getAutoGrade());
		if(StrUtil.isNotBlank(visitVo.getRescueWhereAbouts())) {
			DictRescueWhere queryDictRescueWhere=new DictRescueWhere();
			queryDictRescueWhere.setCode(visitVo.getRescueWhereAbouts());
			QueryWrapper<DictRescueWhere> queryDictRescueWhereWrapper=new QueryWrapper<>();
			queryDictRescueWhereWrapper.setEntity(queryDictRescueWhere);
			DictRescueWhere dictRescueWhere=dictRescueWhereService.getOne(queryDictRescueWhereWrapper);
			if(dictRescueWhere!=null) {
				visitVo.setRescueWhereAboutsName(dictRescueWhere.getName());
			}
		}
		
		
		//获取科室
		if(visitVo.getDepart()!=null) {
				Map<String,Object> map=thirdUtil.getDepartById(visitVo.getDepart());
				if(map!=null) {
					visitVo.setDepartName(StringUtil.toStr(map.get("name")));
				}
		}
		if(visitVo.getComingGradeId()!=null) {
			GradeInfo comingGradeInfo=gradeInfoService.getById(visitVo.getComingGradeId());
			if(comingGradeInfo!=null) {
				visitVo.setComingGradeName(comingGradeInfo.getName());
			}
		}
		if(visitVo.getComingGradeId()!=null) {
			GradeInfo changeGradeInfo=gradeInfoService.getById(visitVo.getChangeGradeId());
			if(changeGradeInfo!=null) {
				visitVo.setChangeGradeName(changeGradeInfo.getName());
			}
		}
		
		if(visitVo.getAutoGradeId()!=null) {
			GradeInfo changeGradeInfo=gradeInfoService.getById(visitVo.getAutoGradeId());
			if(changeGradeInfo!=null) {
				visitVo.setAutoGradeName(changeGradeInfo.getName());
			}
		}
		return visitVo;
	}
	
	@ApiOperation(value = "根据医保卡号读取患者就诊信息",notes = "根据医保卡号读取患者就诊信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "medicalCard",value = "医疗卡号",dataType = "String",paramType = "path",example = "1112",required=true),
	    @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在的医院ID",dataType = "String",paramType = "query",example = "1112",required=true)
	})
    
    
	@GetMapping("medicalCard/{medicalCard}")
	public ResponseData<VisitVo> selectByMedicalCard(@PathVariable String medicalCard,Integer hospitalId){
		if(StrUtil.isEmpty(medicalCard)) {
			throw new ServiceException("患者medicalCard不能为空，请重新确认！");
		}
		if(hospitalId==null) {
			throw new ServiceException("登陆用户所在的医院ID不能为空，请重新确认！");
		}
		PatientInfo queryPatientInfo=new PatientInfo();
		queryPatientInfo.setMedicalCardNumber(medicalCard.trim());
		queryPatientInfo.setHospitalId(hospitalId);
		QueryWrapper<PatientInfo> queryPatientInfoWrapper=new QueryWrapper<>();
		queryPatientInfoWrapper.setEntity(queryPatientInfo);
		PatientInfo patientInfo=patientInfoService.getOne(queryPatientInfoWrapper);
		PatientInfoVo patientInfoVo=null;
		if(patientInfo!=null) {
			patientInfoVo=patientInfoService.getPatientDisplay(patientInfo);
		}else {
			throw new ServiceException("该患者不存在！");
		}
		return ResponseData.success(createVisitVo(null,patientInfoVo));
	}
	
	@ApiOperation(value = "添加离抢信息",notes = "添加离抢信息")
	@PostMapping("")
	public ResponseData<Integer>  add(@RequestBody @Valid RescueInfoDto rescueInfo,BindingResult bindingResult){
		rescueInfo.setId(null);
		Integer id=rescueInfoService.insert(rescueInfo);
		return ResponseData.success(id);
	}
	
	
	
	
	@ApiOperation(value = "根据分诊ID获取离抢信息日志",notes = "根据分诊编号获取离抢信息日志")
	@GetMapping("list/triage/{triageId}")
	public ResponseData<List<RescueLogVo>>  list(@PathVariable("triageId") Integer triageId){
		if(triageId==null) {
			throw new ServiceException("分诊ID不能为空，请重写确认！");
		}
		RescueInfo queryRescueInfo=new RescueInfo();
		queryRescueInfo.setTriageId(triageId);
		QueryWrapper<RescueInfo> queryRescueInfoWrapper=new QueryWrapper<>();
		queryRescueInfoWrapper.setEntity(queryRescueInfo);
		RescueInfo rescueInfo=rescueInfoService.getOne(queryRescueInfoWrapper);
		if(rescueInfo==null) {
			throw new ServiceException("该离抢信息已不存在");
		}
		RescueLog queryRescueLog=new RescueLog();
		queryRescueLog.setRescueId(rescueInfo.getId());
		QueryWrapper<RescueLog> queryRescueLogWrapper=new QueryWrapper<>();
		queryRescueLogWrapper.setEntity(queryRescueLog);
		queryRescueLogWrapper.orderByDesc("BEGIN_TIME");
		List<DictRescueWhere> dicts=dictRescueWhereService.list();
		List<RescueLog> rescueLogs=rescueLogService.list(queryRescueLogWrapper);
		List<RescueLogVo> rescueLogVos=CollUtil.newArrayList();
		if(CollUtil.isNotEmpty(rescueLogs)) {
			for(RescueLog rescueLog:rescueLogs) {
				RescueLogVo rescueLogVo=new RescueLogVo();
				rescueLogVos.add(rescueLogVo);
				BeanUtil.copyProperties(rescueLog, rescueLogVo);
				for(DictRescueWhere dictRescueWhere:dicts) {
					if(dictRescueWhere.getCode().equals(rescueLog.getRescueWhereAbouts())) {
						rescueLogVo.setRescueWhereAboutsName(dictRescueWhere.getName());
						break;
					}
				}
			}
		}
		
		
		return ResponseData.success(rescueLogVos);
	}
}
